<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <card class="car-model-999" title="基本信息" toggle>
        <page-form-row>
          <page-form-item field="clientName" label="企业客户名称" required size="1/3">
            <a-input v-model="form.clientName" placeholder="请输入" :max-length="30" allow-clear />
          </page-form-item>
          <page-form-item label="电子合同认证状态" size="1/3" v-if="routePrams.id">
            <div class="status" :class="getClassName(form)">
              {{ form.ecAuthenticationStatusName }}
            </div>
            <template v-if="form.ecAuthenticationStatus === 0"> 原因: {{ form.authenticationFailedReason }} </template>
          </page-form-item>
          <page-form-item label="签署方式" v-if="routePrams.id">{{ form.contractSignWayName }}</page-form-item>
        </page-form-row>
      </card>
      <card class="car-model-999" title="企业联系人" toggle>
        <page-form-row>
          <page-form-item field="linkman" label="姓名" size="1/3">
            <a-input v-model="form.linkman" placeholder="请输入" :max-length="20" allow-clear />
          </page-form-item>
          <page-form-item field="mobile" label="手机号" size="1/3">
            <a-input v-model="form.mobile" placeholder="请输入" :max-length="11" @keyup="keyupPhone" allow-clear />
          </page-form-item>
        </page-form-row>
      </card>
      <card class="car-model-999" title="发票信息" toggle>
        <page-form-row>
          <page-form-item field="billTitle" label="抬头" size="1/3">
            <a-input v-model="form.billTitle" placeholder="请输入" :max-length="30" allow-clear />
          </page-form-item>
          <page-form-item field="billType" label="发票类型" size="1/3" v-if="clientInfoPageData.InvoiceTypeEnum">
            <a-select v-model="form.billType" placeholder="请选择" allow-clear>
              <a-option v-for="item in clientInfoPageData.InvoiceTypeEnum" :key="item.value" :value="item.value" :label="item.label" />
            </a-select>
          </page-form-item>
          <page-form-item field="taxpayerId" label="纳税人识别号" size="1/3">
            <a-input v-model="form.taxpayerId" placeholder="请输入" :max-length="30" allow-clear />
          </page-form-item>
          <page-form-item field="address" label="公司地址" size="1/3">
            <a-input v-model="form.address" placeholder="请输入" :max-length="50" allow-clear />
          </page-form-item>
          <page-form-item field="billReceiverPhone" label="联系电话" size="1/3">
            <a-input v-model="form.billReceiverPhone" placeholder="请输入" :max-length="20" allow-clear />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="合同信息" toggle :showDivider="false">
        <div class="contract-list" v-if="form.contractList">
          <template v-for="(item, index) in form.contractList" :key="index">
            <div class="flex upload-wrapper con-item">
              <drag-upload
                style="margin-right: 20px"
                v-model="item.fileId"
                :maxMB="50"
                class="upload-content"
                @change="dragChange"
                :key="item.uid"
              />
              <div class="flex-1">
                <page-form-row>
                  <page-form-item label="合同有效期" size="1/2">
                    <i-range-picker v-model="item.dateRange" class="w-full" @change="(val) => changeDateFn(val, index)" />
                  </page-form-item>
                  <page-form-item label="签约人" size="1/2">
                    <!-- 调试时，可插入参数orgIdList: [70] -->
                    <remote-select
                      v-model="item.signUserId"
                      :params="{ likeRealname: item.signUserName }"
                      type="client_clientInfo"
                      v-on="{
                        change: signUserChange(item),
                      }"
                    />
                  </page-form-item>
                </page-form-row>
              </div>
              <div class="flex justify-center buttons">
                <a-space :size="16">
                  <a-button status="danger" @click="delFn(index)" v-if="index != 0">
                    <template #icon>
                      <icon-minus />
                    </template>
                    删除当前合同
                  </a-button>
                  <a-button type="primary" @click="addFn" v-if="showAddBtnFn(index)">
                    <template #icon>
                      <icon-plus />
                    </template>
                    添加合同
                  </a-button>
                </a-space>
              </div>
            </div>
            <a-divider v-if="index != form.contractList.length - 1" style="margin: 20px 0" />
          </template>
        </div>
      </card>
    </page-form>
  </div>

  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>

<script setup name="EpClientForm">
  import { ref, nextTick, watch } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { getDetail, clientsave, clientupdate } from '@/api/market/clientInfo'
  // import contractlist from '@/views/market/bazaar/clientInfo/form/components/contract.vue'
  import useNavigate from '@/hooks/useNavigate'
  import { cloneDeep } from 'lodash-es'

  const { navigateBack } = useNavigate()
  const route = useRoute()
  const routePrams = route.params

  // UID 计数器
  const UIDCount = ref(0)
  // 获取 UID
  const getUID = () => {
    return Date.now().toString() + '_' + UIDCount.value++
  }

  const changeDateFn = (val, index) => {
    console.log(val)
    console.log(index)
    form.value.contractList[index].dateRange = val

    form.value.contractList[index].startTime = val[0]
    form.value.contractList[index].endTime = val[1]
  }
  // 是否显示 添加按钮
  const showAddBtnFn = (index) => {
    return index == form.value.contractList.length - 1
  }
  const signUserChange = (record) => {
    return function (value, option) {
      record.signUserId = option.id
      record.signUserName = option.realname
    }
  }
  // 添加
  const addFn = () => {
    if (form.value.contractList.length < 21) {
      form.value.contractList.push({
        fileId: '',
        startTime: '',
        endTime: '',
        dateRange: [],
        signUserId: '',
        signUserName: '',
        uid: getUID(),
      })
    } else {
      Message.error('最多添加20条')
    }
  }
  // 删除
  const delFn = (index) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      bodyStyle: {
        'text-align': 'center',
      },
      content: '确认删除吗？',
      onOk: () => {
        nextTick(() => {
          form.value.contractList.splice(index, 1)
          // form.value.contractList = form.value.contractList.filter((item) => item != form.value.contractList[index])
          console.log(form.value.contractList)
        })
      },
    })
  }
  const dragChange = (e) => {
    console.log(e)
  }

  const cloneDeepResult = ref()
  const getDetails = (id) => {
    getDetail({ id: id }).then((res) => {
      form.value = res.result
      cloneDeepResult.value = cloneDeep(res.result)
      if (!form.value.contractList || form.value.contractList.length == 0) {
        form.value.contractList = [
          {
            fileId: '',
            startTime: '',
            endTime: '',
            signUserId: '',
            signUserName: '',
            uid: getUID(),
          },
        ]
      } else {
        // 合并时间
        form.value.contractList.forEach((i) => {
          i.dateRange = [i.startTime, i.endTime]
          i.uid = getUID()
        })
      }
    })
  }

  const getClassName = (item) => {
    // -1: 未认证 0: 认证失败 1: 认证成功 2: 认证中
    if (item.ecAuthenticationStatus === -1) {
      return 'status-unauth'
    } else if (item.ecAuthenticationStatus === 0) {
      return 'status-failed'
    } else if (item.ecAuthenticationStatus === 1) {
      return 'status-success'
    } else if (item.ecAuthenticationStatus === 2) {
      return 'status-wait'
    }
  }

  console.log(routePrams)
  const pageType = ref(null)
  if (routePrams.id) {
    pageType.value = 'edit'
    getDetails(routePrams.id)
  } else {
    pageType.value = 'create'
  }

  const form = ref({
    contractList: [
      {
        fileId: '',
        startTime: '',
        endTime: '',
        signUserId: '',
        signUserName: '',
        uid: getUID(),
      },
    ],
  })
  const rules = {
    clientName: { required: true, message: '请填写企业客户名称' },
  }
  const keyupPhone = () => {
    let result = form.value.mobile
    form.value.mobile = result.replace(/\D/g, '')
  }
  const clientInfoPageData = usePageDict('clientInfoPageData')
  console.log(clientInfoPageData)

  /**
   * 判断对象的值是不是全为空
   */
  const objectValueAllEmpty = (object) => {
    var isEmpty = true
    Object.keys(object).forEach(function (x) {
      if (object[x] != null && object[x] != '') {
        isEmpty = false
      }
    })
    return isEmpty
  }

  const isChangeClientName = ref(false)
  watch(
    () => form.value.clientName,
    (val) => {
      if (routePrams.id) {
        if (val != cloneDeepResult.value.clientName) {
          isChangeClientName.value = true
        }
        if (val == cloneDeepResult.value.clientName) {
          isChangeClientName.value = false
        }
      }
    }
  )

  const isChangeMobile = ref(false)
  watch(
    () => form.value.mobile,
    (val) => {
      if (routePrams.id) {
        if (val != cloneDeepResult.value.mobile) {
          isChangeMobile.value = true
        }
        if (val == cloneDeepResult.value.mobile) {
          isChangeMobile.value = false
        }
      }
    }
  )

  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }

        const submitTmp = () => {
          form.value.contractList.forEach((el, index) => {
            if (objectValueAllEmpty(el)) {
              param.contractList.splice(index, 1)
            }
          })
          okLoading.value = true
          if (pageType.value == 'create') {
            clientsave(param)
              .then(() => {
                noticeSuccess()
                navigateBack()
              })
              .finally(() => {
                okLoading.value = false
              })
          } else {
            clientupdate(param)
              .then(() => {
                noticeSuccess()
                navigateBack()
              })
              .finally(() => {
                okLoading.value = false
              })
          }
        }

        console.log(isChangeClientName.value, isChangeMobile.value)
        if (
          (isChangeClientName.value || isChangeMobile.value) &&
          (form.value.ecAuthenticationStatus === 0 || form.value.ecAuthenticationStatus === 1 || form.value.ecAuthenticationStatus === 2)
        ) {
          let content = ''
          if (isChangeClientName.value) {
            content = '企业已发起电子合同认证，如修改企业客户名称，下次签署合同时，需重新认证，是否修改？'
          }
          if (isChangeMobile.value) {
            content = '企业已发起电子合同认证，修改电话号码会影响盖章操作，为避免造成损失，请修改后尽快联系我司工作人员'
          }
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content,
            onOk: () => {
              submitTmp()
            },
            // onCancel: () => {
            //   param.clientName = cloneDeepResult.value.clientName
            //   param.mobile = cloneDeepResult.value.mobile
            //   submitTmp()
            // },
          })
        } else {
          submitTmp()
        }
      }
    })
  }
</script>

<style lang="less" scoped>
  .status {
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 76px;
    height: 20px;
    padding: 0 8px;
    font-size: 12px;
    font-weight: 500;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid;
    color: rgba(185, 187, 196, 1);
    border-color: rgba(229, 230, 235, 1);
    background-color: rgba(242, 243, 245, 1);

    &.status-unauth {
      color: rgba(185, 187, 196, 1);
      border-color: rgba(229, 230, 235, 1);
      background-color: rgba(242, 243, 245, 1);
    }
    &.status-failed {
      color: rgba(245, 63, 63, 1);
      border-color: rgba(245, 63, 63, 1);
      background-color: rgba(255, 236, 232, 1);
    }
    &.status-success {
      color: rgba(0, 180, 42, 1);
      border-color: rgba(0, 180, 42, 1);
      background-color: rgba(232, 255, 234, 1);
    }
    &.status-wait {
      color: rgba(255, 125, 0, 1);
      border-color: rgba(255, 125, 0, 1);
      background-color: rgba(255, 247, 232, 1);
    }
  }
  .upload-width {
    width: 37%;
  }
  .mt-20px {
    margin-top: 16px;
  }

  .con-item {
    position: relative;
    .buttons {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
  .status-name {
    color: red;
  }
</style>
